// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/substrait/substrait_extension_collector.h>

namespace kumo::pollux::substrait {
    int SubstraitExtensionCollector::getReferenceNumber(
        const std::string &functionName,
        const std::vector<TypePtr> &arguments) {
        const auto &substraitFunctionSignature =
                PolluxSubstraitSignature::toSubstraitSignature(functionName, arguments);
        // TODO: Currently we treat all pollux registry based function signatures as
        // custom substrait extension, so no uri link and leave it as empty.
        return getReferenceNumber({"", substraitFunctionSignature});
    }

    int SubstraitExtensionCollector::getReferenceNumber(
        const std::string &functionName,
        const std::vector<TypePtr> &arguments,
        const core::AggregationNode::Step /* aggregationStep */) {
        // TODO: Ignore aggregationStep for now, will refactor when introduce pollux
        // registry for function signature binding
        return getReferenceNumber(functionName, arguments);
    }

    template<typename T>
    bool SubstraitExtensionCollector::BiDirectionHashMap<T>::putIfAbsent(
        const int &key,
        const T &value) {
        if (forwardMap_.find(key) == forwardMap_.end() &&
            reverseMap_.find(value) == reverseMap_.end()) {
            forwardMap_[key] = value;
            reverseMap_[value] = key;
            return true;
        }
        return false;
    }

    void SubstraitExtensionCollector::addExtensionsToPlan(
        ::substrait::Plan *plan) const {
        using SimpleExtensionURI = ::substrait::extensions::SimpleExtensionURI;
        // Currently we don't introduce any substrait extension YAML files, so always
        // only have one URI.
        SimpleExtensionURI *extensionUri = plan->add_extension_uris();
        extensionUri->set_extension_uri_anchor(1);

        for (const auto &[referenceNum, functionId]:
             extensionFunctions_->forwardMap()) {
            auto extensionFunction =
                    plan->add_extensions()->mutable_extension_function();
            extensionFunction->set_extension_uri_reference(
                extensionUri->extension_uri_anchor());
            extensionFunction->set_function_anchor(referenceNum);
            extensionFunction->set_name(functionId.signature);
        }
    }

    SubstraitExtensionCollector::SubstraitExtensionCollector() {
        extensionFunctions_ =
                std::make_shared<BiDirectionHashMap<ExtensionFunctionId> >();
    }

    int SubstraitExtensionCollector::getReferenceNumber(
        const ExtensionFunctionId &extensionFunctionId) {
        const auto &extensionFunctionAnchorIt =
                extensionFunctions_->reverseMap().find(extensionFunctionId);
        if (extensionFunctionAnchorIt != extensionFunctions_->reverseMap().end()) {
            return extensionFunctionAnchorIt->second;
        }
        ++functionReferenceNumber;
        extensionFunctions_->putIfAbsent(
            functionReferenceNumber, extensionFunctionId);
        return functionReferenceNumber;
    }
} // namespace kumo::pollux::substrait
